package com.gui.helper;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * CustomTableModel class provides a dynamic table model to be loaded to the table
 * component in the users view.
 * @author sithum
 */
public class CustomTableModel extends AbstractTableModel {

    //Contains the column names of the table.
    private String[] columnNames;
    //Contains the data to be loaded to the table.
    private Object[][] tableData;
    private JTable contentTable;

    /**
     * Instantiates a new table model object with the specified column names and
     * data.
     * @param java.lang.String[]
     * @param java.lang.Object[][]
     */
    public CustomTableModel(String[] columnNames, Object[][] tableData) {
        this.columnNames = columnNames;
        this.tableData = tableData;
    }

    @Override
    public int getRowCount() {
        return getTableData().length;
    }

    @Override
    public int getColumnCount() {
        return getColumnNames().length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return getTableData()[rowIndex][columnIndex];
    }

    /**
     * JTable uses this method to detemine the default renderer/editor for each
     * cell of the table. If this method is not overriden cells contain boolean
     * values will contain text instead of checkboxes.
     * @param int columnIndex
     * @return java.lang.Class
     */
    @Override
    public Class getColumnClass(int columnIndex) {
        return this.getValueAt(0, columnIndex).getClass();
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if (columnIndex < (getColumnNames().length - 1)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        getTableData()[rowIndex][columnIndex] = aValue;
        fireTableCellUpdated(rowIndex, columnIndex);
    }

    @Override
    public String getColumnName(int columnIndex) {
        return getColumnNames()[columnIndex];
    }

    /**
     * @return the contentTable
     */
    public JTable getContentTable() {
        return contentTable;
    }

    /**
     * @param contentTable the contentTable to set
     */
    public void setContentTable(JTable contentTable) {
        this.contentTable = contentTable;
    }

    /**
     * @return the columnNames
     */
    public String[] getColumnNames() {
        return columnNames;
    }

    /**
     * @param columnNames the columnNames to set
     */
    public void setColumnNames(String[] columnNames) {
        this.columnNames = columnNames;
    }

    /**
     * @return the tableData
     */
    public Object[][] getTableData() {
        return tableData;
    }

    /**
     * @param tableData the tableData to set
     */
    public void setTableData(Object[][] tableData) {
        this.tableData = tableData;
    }
}
